/**
 *      存盘 数据 类   
 */
export default class Save_data {
    private static file_name = "shaokao_1";

    private name: string;
    private data: any;

    /**********************************************
     *          全局类 函数
     **********************************************/
    private static curr_save: Save_data;

    public static init_save() {
        if (Save_data.curr_save != null) return;

        Save_data.curr_save = new Save_data();
        Save_data.curr_save.name = Save_data.file_name;

        Save_data.curr_save.data = Save_data._load_localData(Save_data.curr_save.name);
        if (Save_data.curr_save.data == null) {
            Save_data.new_data();
        }
    }

    public static new_data(): void {
        let d: any = {};
        d.last_save_time = 0; // 最后一次 存盘时间
        Save_data.curr_save.data = d;
        
    }

    /**
     *    异步存盘
     */
    private static _save_thread = null;
    public static save(): void {
        if (Save_data._save_thread != null) {
            return;
        }
        Save_data._save_thread = setInterval(() => {
            clearInterval(Save_data._save_thread);
            Save_data._save_thread = null;
            Save_data.curr_save.data.last_save_time = new Date().getTime();
            Save_data._save_localData(Save_data.curr_save.data, Save_data.curr_save.name);
        }, 0);
    }

    /**
     *    同步存盘
     */
    public static save_sync(): void {
        Save_data.curr_save.data.last_save_time = new Date().getTime();
        Save_data._save_localData(Save_data.curr_save.data, Save_data.curr_save.name);
    }

    public static getData(): any {
        if (Save_data.curr_save == null) {
            Save_data.init_save();
        }
        return Save_data.curr_save.data;
    }

    public static clean_save() {
        Save_data._del_localData(Save_data.file_name);
        Save_data.curr_save = null;
        Save_data.init_save();
    }

    /******************************************************
     *             通用 工具类 函数
     ******************************************************/
    private static _save_localData(baseObj: any, nameString: string): void {
        var baseData = JSON.stringify(baseObj);
        cc.sys.localStorage.setItem(nameString, baseData);
    };

    private static _load_localData(nameString: string): any {
        var baseDataa = cc.sys.localStorage.getItem(nameString); //从本地读取数据
        if (baseDataa == null || baseDataa == "") return null;
        baseDataa = JSON.parse(baseDataa); //将string转换成json
        return baseDataa;
    };
	
    private static _del_localData(nameString: string): void {
        cc.sys.localStorage.removeItem(nameString);
    };
	
}
